﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json.Linq;

namespace Web.TableHtmlGeterate
{
    /// <summary>
    /// 数据抓取
    /// </summary>
    public class DataCapture
    {

        /// <summary>
        /// 获取同行业数据
        /// </summary>
        /// <param name="industryCode">行业代码</param>
        /// <returns>行业数据集合</returns>
        public static List<Com.Stockstar.Quote.Model.Quote.IndustryIndex> GetIndustryIndexDatasInCache(string industryCode)
        {
            List<Com.Stockstar.Quote.Model.Quote.IndustryIndex> list = null;
            object obj = CacheManager.GetCache(industryCode);
            if (obj != null)
            {
                return obj as List<Com.Stockstar.Quote.Model.Quote.IndustryIndex>;
            }
            else
            {
                list = GetIndustryIndexDatas(industryCode);
                CacheManager.AddCache(industryCode, list, App_Codes.GetCount.CacheTime);
                return list;
            }
        }


        /// <summary>
        /// 获取同行业数据
        /// </summary>
        /// <param name="industryCode">行业代码</param>
        /// <returns>行业数据集合</returns>
        public static List<Com.Stockstar.Quote.Model.Quote.IndustryIndex> GetIndustryIndexDatas(string industryCode)
        {
            List<Com.Stockstar.Quote.Model.Quote.IndustryIndex> list = Com.Stockstar.Quote.Common.Quote.IndustryIndexSingleton.Instance.IndustryIndexList.Where(a => a.Code.Equals(industryCode)).Take(5).ToList();
            return list;
        }

        /// <summary>
        /// 获取同行业个股数据
        /// </summary>
        /// <param name="industryCode"></param>
        /// <returns></returns>
        public static List<Com.Stockstar.Quote.Model.Quote.QuoteSnap> GetQuoteSnapDatasInCache(string industryCode)
        {
            object obj = CacheManager.GetCache(industryCode);
            if (obj != null)
            {
                return obj as List<Com.Stockstar.Quote.Model.Quote.QuoteSnap>;
            }
            else
            {
                var list = GetQuoteSnapDatas(industryCode);
                CacheManager.AddCache(industryCode, list, App_Codes.GetCount.CacheTime);
                return list;
            }
        }


        /// <summary>
        /// 获取同行业个股数据
        /// </summary>
        /// <param name="industryCode"></param>
        /// <returns></returns>
        public static List<Com.Stockstar.Quote.Model.Quote.QuoteSnap> GetQuoteSnapDatas(string industryCode)
        {
            List<Com.Stockstar.Quote.Model.Quote.QuoteSnap> list = Com.Stockstar.Quote.Common.Quote.SnapSingleton.Instance.SnapList.Where(a => a.IndustryCode != null).Where(a => a.IndustryCode.Equals(industryCode)).OrderByDescending(a => a.UpDownRate).Take(5).ToList();
            return list;
        }

        public static List<IndexFutures> GetIndexFuturesDatasInCache(string[] indexFuturesCodes)
        {
            string cacheString = "";
            foreach (string s in indexFuturesCodes)
            {
                cacheString += s;
            }
            object obj = CacheManager.GetCache(cacheString);
            if (obj != null)
            {
                return obj as List<IndexFutures>;
            }
            else
            {
                var list = GetIndexFuturesDatas(indexFuturesCodes);
                CacheManager.AddCache(cacheString, list, App_Codes.GetCount.CacheTime);
                return list;
            }
        }


        /// <summary>
        /// 得到关联期货的数据集合
        /// </summary>
        /// <param name="indexFuturesCodes">相关期货的代码</param>
        /// <returns></returns>
        public static List<IndexFutures> GetIndexFuturesDatas(string[] indexFuturesCodes)
        {
            List<IndexFutures> indexFuturesList = new List<IndexFutures>();

            F10ParamEntity param = new F10ParamEntity("Quote", "FEED_FEX_QUOTESNAP", 2);

            string codes = "";
            //如果传入的参数为空或者为NULL，则返回空集合
            if (indexFuturesCodes.Length == 0 || indexFuturesCodes == null)
            {
                return indexFuturesList;
            }

            if (indexFuturesCodes.Length > 1)
            {
                foreach (string code in indexFuturesCodes)
                {
                    codes += code + ",";
                }
                codes = codes.Substring(0, codes.Length - 1);
            }
            else
            {
                codes = indexFuturesCodes[0];
            }

            param.Filters = new List<string>() { "CODE-in-str=" + codes };
            param.OrderBy = "CODE asc";
            JToken clientData = null;
            int totalCount = 0;
            F10Query.TryParse(param, false, out clientData, out totalCount);
            if (clientData != null && totalCount > 0)
            {
                for (int i = 0; i < clientData.Count(); i++)
                {
                    IndexFutures future = new IndexFutures();
                    future.CODE = F10JTokenExt.J_String(clientData[i], "CODE");
                    future.NEW = (double)clientData[i]["NEW"];//期指最新价保留1位小数
                    future.NAME = F10JTokenExt.J_String(clientData[i], "NAME");
                    future.HOLD = (long)clientData[i]["HOLD"];
                    future.JYS = F10JTokenExt.J_String(clientData[i], "JYS");
                    future.OPEN = (double)clientData[i]["OPEN"];
                    future.VOLUME = (long)clientData[i]["VOLUME"];
                    future.LAST_AV = (double)clientData[i]["LAST_AV"];
                    if (future.JYS.Equals("期指"))
                    {
                        future.LAST_AV = (double)clientData[i]["CLOSE"];//昨收
                    }
                    else if (future.JYS.Equals("XFFEX"))
                    {
                        future.LAST_AV = (double)clientData[i]["LAST_AV"];//昨收
                    }

                    future.PXCHG = future.NEW - future.LAST_AV;
                    future.Change = future.PXCHG / future.LAST_AV * 100;//单位%
                    indexFuturesList.Add(future);
                }
            }
            else
            {
                log4net.LogManager.GetLogger("david").Error("关联期货获取数据失败");
            }


            return indexFuturesList;
        }


        /// <summary>
        /// 获取指数近期数据的集合
        /// </summary>
        /// <param name="tableName">接口名称</param>
        /// <param name="filters">过滤条件，以逗号分割不同条件</param>
        /// <param name="dateColumn">排序字段（这个排序字段还用来显示在前台），以逗号分割不同条件</param>
        /// <param name="priceColumns">读取的价格字段</param>
        /// <param name="count">读取条数</param>
        /// <returns></returns>
        public static List<App_Codes.Prices> GetCurrentDatas(string tableName, string filters, string dateColumn, List<string> priceColumns, int count = 6)
        {
            List<App_Codes.Prices> datas = new List<App_Codes.Prices>();
            F10ParamEntity entity = new F10ParamEntity(2);
            entity.Filters = new List<string>();

            if (!string.IsNullOrEmpty(filters))
            {

                string[] _filters = filters.Split(new char[] { ',' });
                foreach (string filter in _filters)
                {
                    entity.Filters.Add(filter);
                }
            }

            //  foreach (string str in priceColumns)
            // {
            string temp = priceColumns[0] + "-gt-int=0";
            entity.Filters.Add(temp);
            //  }
            entity.TableName = tableName;
            entity.Prefix = "Base";
            //  entity.Filters
            entity.Limit = count;

            string[] keys = dateColumn.Split(new char[] { ',' });

            string _sort = "";
            if (keys.Length > 1)
            {
                foreach (string key in keys)
                {
                    if (!string.IsNullOrEmpty(key))
                    {
                        _sort += key + " DESC,";
                    }
                }
            }
            else
            {
                _sort = dateColumn + " DESC";
            }

            entity.OrderBy = _sort;



            Newtonsoft.Json.Linq.JToken token;



            int totalCount;


            bool result = F10Query.TryParse(entity, false, out token, out totalCount);
            if (totalCount < count)
            {
                count = totalCount;
            }
            if (result)
            {
                for (int i = 0; i < count; i++)
                {
                    float _temp = 0f;
                    DateTime _dtemp = DateTime.Now;


                    App_Codes.Prices data = new App_Codes.Prices();

                    List<double> _prices = new List<double>();
                    //如果传入的排序字段有多个，则根据Sort的关键字组装需要显示的日期
                    if (dateColumn.IndexOf(",") > 0)
                    {

                        string _tempDateTimeString = "";
                        foreach (string key in keys)
                        {
                            int _tempInteger = 0;
                            if (!string.IsNullOrEmpty(key))
                            {
                                int _value = token[i].J_Integer(key, _tempInteger);
                                _tempDateTimeString += _value + "-";
                            }
                        }
                        //   _tempDateTimeString = _tempDateTimeString.Substring(0, _tempDateTimeString.Length - 1);
                        data.EDATE = Convert.ToDateTime(_tempDateTimeString + "1");
                    }
                    else
                    {
                        data.EDATE = token[i].J_DateTime(dateColumn, _dtemp);
                    }


                    //只读取一个字段，表明这是一个需要计算差值的数据集合
                    if (priceColumns.Count == 1)
                    {
                        _prices.Add(Math.Round(token[i].J_Float(priceColumns.First(), _temp), 2));

                        if (i > 4)
                        {
                            //第六天不需要处理涨跌额这个字段
                            _prices.Add(-1);
                        }
                        else
                        {
                            _prices.Add(Math.Round(token[i].J_Float(priceColumns.First(), _temp) - token[i + 1].J_Float(priceColumns.First(), _temp), 2));
                        }
                    }
                    //读取多个字段
                    else
                    {
                        foreach (string key in priceColumns)
                        {
                            _prices.Add(Math.Round(token[i].J_Double(key, _temp), 2));
                        }
                    }


                    data.PriceList = _prices;

                    datas.Add(data);
                }
            }
            else
            {
                log4net.LogManager.GetLogger("david").Error("近期数据获取数据失败");
            }
            datas = datas.OrderBy(a => a.EDATE).ToList();
            return datas;

        }

    }
}